package com.health.webservices;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.json.JSONObject;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParserException;

import com.health.NovaApplication;
import com.health.tools.GlobalConts;
import com.health.tools.OnWebServiceLinstener;
import com.health.tools.SPUtil;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

//更新本机构及管理人员
//同步本机构用户
public class ZCMWebService implements OnWebServiceLinstener {
	// private static final String WSDL_URI =
	// "http://192.168.10.154:8081/ehr/webservice/getInfoByOrgUser";
//	private static final String WSDL_URI = ;
	private static final String NAMESPACE = "http://webservice.zy.com/";
	private static final String NAMESPACE2 = "http://tempuri.org/";
	private static final String METHOD_NAME = "getHardware";
	private static final String SOAP_ACTION = NAMESPACE+METHOD_NAME;
	private SoapObject mRequest;
	private SoapSerializationEnvelope mEnvelope;
	@SuppressLint("SimpleDateFormat")
	private SimpleDateFormat mSdf = new SimpleDateFormat("yyyy-MM-dd");
	private OnWebServiceLinstener mLinstener;
	public int mSyncCount = 1;
	public int mDataSize = 0;
	private String imeiId = "";
	private Context mContext;

	public void setOnWebServiceLinstener(OnWebServiceLinstener linstener) {
		this.mLinstener = linstener;
	}

	public ZCMWebService(Context context) {
		this.mContext = context;
	}

	public void synchrodata(String orgid) throws Exception {
		this.imeiId = orgid;
		new Thread(networkTask).start();

	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle data = msg.getData();
			String val = data.getString("value");
			Log.i("mylog", "请求结果为-->" + val);
			// TODO
			// UI界面的更新等相关操作
		}
	};
	//全国通用地址
//	public static final String URL_POST_SHANXIN_ADDRESS = "http://118.190.114.57:8082/novaInt/";
	/**
	 * 网络操作相关的子线程
	 */
	Runnable networkTask = new Runnable() {

		@Override
		public void run() {
			try {
				mSyncCount = 1;
				mDataSize = 0;
				mRequest = new SoapObject(NAMESPACE, METHOD_NAME);
				mEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);
				Log.e("imeiId", imeiId);
				mRequest.addProperty("hardware_code", imeiId);
//				Element[] header = new Element[1];
//				header[0] = new Element().createElement(NAMESPACE, "user");
//				header[0].addChild("user", "pad");
//
//				header[1] = new Element().createElement(NAMESPACE, "module");
//				header[1].setAttribute(NAMESPACE, "module", "gxy");

//				header[2] = new Element().createElement(NAMESPACE, "token");
//				header[2].setAttribute(NAMESPACE, "token",
//						"eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJub3ZhdGVjaGJpbyIsImF1ZCI6InBhZCIsImlhdCI6MTUwNDkzODEzMSwic3ViIjoiZ3h5In0.8SfiVonZlH_cY_abEeWKWGwcrIKHKskuAnRmifn8eVc");
//				mEnvelope.headerOut = buildAuthHeader();

//				Element[] header = new Element[1];
//				header[0] = new Element().createElement("", "head");
//				Element user = new Element().createElement("", "user");
//				user.addChild(Node.TEXT, "pad");
//				Element module = new Element().createElement("", "module");
//				module.addChild(Node.TEXT, "gxy");
//				Element token = new Element().createElement("", "token");
//				token.addChild(Node.TEXT,
//						"eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJub3ZhdGVjaGJpbyIsImF1ZCI6InBhZCIsImlhdCI6MTUwNDkzODEzMSwic3ViIjoiZ3h5In0.8SfiVonZlH_cY_abEeWKWGwcrIKHKskuAnRmifn8eVc");
//
//				header[0].addChild(Node.ELEMENT, user);
//				header[0].addChild(Node.ELEMENT, module);
//				header[0].addChild(Node.ELEMENT, token);
//				mEnvelope.headerOut = header;
				
				
				mEnvelope.bodyOut = mRequest;
				mEnvelope.dotNet = false;
				
				HttpTransportSE httpTransportSE = new HttpTransportSE(GlobalConts.getUrlPost() + "webservice/getHardware");
				System.out.print("获取注册码地址"+GlobalConts.getUrlPost() + "webservice/getHardware");

				httpTransportSE.call(SOAP_ACTION, mEnvelope);

				start("正在获取注册码...");
				try {
					SoapPrimitive response = (SoapPrimitive) mEnvelope.getResponse();// 获得返回对象
//					 SoapObject response = (SoapObject)
//					 mEnvelope.bodyIn ;// 获得返回对象
//					  Object response = ( Object)
//							 mEnvelope.bodyIn;// 获得返回对象
					Log.e("顶顶顶顶---", "数据：" + response);
					if (response != null) {
						String strres = response.toString();
						//{"totalSize":1,"state": "机器码注册信息","success":"true","data":"370188D60099003"}
						JSONObject obj = new JSONObject(strres.toString());
						if(obj.has("success")){
							if("true".equals(obj.getString("success"))){
								String str_xzh=obj.getString("data");
								if(TextUtils.isEmpty(str_xzh)){
								}else{
									saveZCMData(str_xzh);
								}
								String tokens = obj.getString("token");
								if (TextUtils.isEmpty(tokens)) {
									SPUtil.setToken(mContext, "");
								}else{
									SPUtil.setRegisterImei(mContext, imeiId);
									SPUtil.setToken(mContext, tokens);
								}
								Log.e("顶顶顶顶---", str_xzh + "---"+ SPUtil.getRegisterImei(mContext)+"---"+SPUtil.getToken(mContext)+SPUtil.getRegisterZCMAll(mContext));
							}
							
						}
						complete("数据同步完成");
					}
				} catch (Exception e) {
					e.printStackTrace();
					complete("数据同步失败");
				}

			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				onError("IOException | XmlPullParserException" + e.getMessage());
				complete("数据同步失败");
			} catch (Exception e) {
				e.printStackTrace();
				onError("Exception" + e.getMessage());
				complete("数据同步失败");
			}
		}
	};

	@Override
	public void start(String message) {
		if (mLinstener != null) {
			mLinstener.start(message);
		}
	}

	@Override
	public void onSynchronize(String message, int syncCount, int dataSize) {
		if (mLinstener != null) {
			mLinstener.onSynchronize(message, syncCount, mDataSize);
		}
	}

	@Override
	public void complete(String message) {
		if (mLinstener != null) {
			mLinstener.complete(message);
		}
	}

	@Override
	public void onError(String message) {
		if (mLinstener != null) {
			mLinstener.onError(message);
		}
	}

	public void saveZCMData(String str_imei) {
		// 获得SharedPreferences.Editor对象
		Log.e("saveZCMData()", str_imei);
		SPUtil.setRegisterZCMAll(mContext, str_imei);
		if (str_imei.length() > 6) {
			SPUtil.setRegisterXZQ(mContext, str_imei.substring(0, 6));
		} else {
			SPUtil.setRegisterXZQ(mContext, str_imei);
		}
	}


	@Override
	public void onUpload() {
		// TODO Auto-generated method stub

	}

	private  Element[] buildAuthHeader() {
		Element[] hElement = new Element[1];
//		header[0] = new Element().createElement(NAMESPACE, "user");
		  hElement[0] = new Element().createElement(NAMESPACE2, "CertificationProxy");
		 
		Element userElement = new Element().createElement(NAMESPACE2, "user");
//		userElement.setAttribute(NAMESPACE2,"user","pad");     
		userElement.setName("user");
		userElement.addChild(org.kxml2.kdom.Node.TEXT, "pad");
		
		Element moduleElement = new Element().createElement(NAMESPACE2, "module");
		moduleElement.setName("module");
		moduleElement.addChild(org.kxml2.kdom.Node.TEXT, "gxy");
		
		
		Element tokenElement = new Element().createElement(NAMESPACE2, "token");
		tokenElement.setName("token");
		tokenElement.addChild(org.kxml2.kdom.Node.TEXT, "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJub3ZhdGVjaGJpbyIsImF1ZCI6InBhZCIsImlhdCI6MTUwNDkzODEzMSwic3ViIjoiZ3h5In0.8SfiVonZlH_cY_abEeWKWGwcrIKHKskuAnRmifn8eVc");
		hElement[0].addChild(org.kxml2.kdom.Node.ELEMENT, userElement);
		hElement[0].addChild(org.kxml2.kdom.Node.ELEMENT, moduleElement);
		hElement[0].addChild(org.kxml2.kdom.Node.ELEMENT, tokenElement);
		return hElement;
	}
}
